package io.xccit.race.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.xccit.race.mapper.RaceCompetitionSignupMapper;
import io.xccit.race.domain.RaceCompetitionSignup;
import io.xccit.race.service.IRaceCompetitionSignupService;
import io.xccit.race.service.IRaceCompetitionRulesService;
import io.xccit.race.service.IRaceCompetitionTeamMemberService;
import io.xccit.race.domain.RaceCompetitionTeamMember;
import io.xccit.common.utils.SecurityUtils;

/**
 * 竞赛报名信息Service业务层处理
 * 
 * @author ywx
 * @date 2025-10-10
 */
@Service
public class RaceCompetitionSignupServiceImpl implements IRaceCompetitionSignupService 
{
    @Autowired
    private RaceCompetitionSignupMapper raceCompetitionSignupMapper;
    
    @Autowired
    private IRaceCompetitionRulesService raceCompetitionRulesService;
    
    @Autowired
    private IRaceCompetitionTeamMemberService raceCompetitionTeamMemberService;

    /**
     * 查询竞赛报名信息
     * 
     * @param id 竞赛报名信息主键
     * @return 竞赛报名信息
     */
    @Override
    public RaceCompetitionSignup selectRaceCompetitionSignupById(Long id)
    {
        return raceCompetitionSignupMapper.selectRaceCompetitionSignupById(id);
    }

    /**
     * 查询竞赛报名信息列表
     * 
     * @param raceCompetitionSignup 竞赛报名信息
     * @return 竞赛报名信息
     */
    @Override
    public List<RaceCompetitionSignup> selectRaceCompetitionSignupList(RaceCompetitionSignup raceCompetitionSignup)
    {
        return raceCompetitionSignupMapper.selectRaceCompetitionSignupList(raceCompetitionSignup);
    }

    /**
     * 新增竞赛报名信息
     * 
     * @param raceCompetitionSignup 竞赛报名信息
     * @return 结果
     */
    @Override
    public int insertRaceCompetitionSignup(RaceCompetitionSignup raceCompetitionSignup)
    {
        // 调试：打印接收到的数据
        System.out.println("=== 新增报名信息调试 ===");
        System.out.println("报名类型: " + raceCompetitionSignup.getSignupType());
        System.out.println("队长姓名: " + raceCompetitionSignup.getLeaderName());
        System.out.println("队长学号: " + raceCompetitionSignup.getLeaderStudentId());
        System.out.println("队长身份证: " + raceCompetitionSignup.getLeaderIdCard());
        System.out.println("队长身份证URL: " + raceCompetitionSignup.getLeaderIdCardUrl());
        
        // 检查是否重复报名
        if (checkDuplicateSignup(raceCompetitionSignup)) {
            throw new RuntimeException("该用户已报名此竞赛，请勿重复报名");
        }
        
        // 设置当前用户ID
        raceCompetitionSignup.setUserId(SecurityUtils.getUserId());
        raceCompetitionSignup.setCreateTime(new Date());
        raceCompetitionSignup.setDelFlag("0");
        raceCompetitionSignup.setStatus(0); // 默认待审核状态
        
        // 设置团队队长标识和人数限制检查
        if (raceCompetitionSignup.getSignupType() == 2) { // 团队赛
            raceCompetitionSignup.setTeamLeader(1); // 默认队长
            
            // 将队长信息映射到报名信息表字段
            if (raceCompetitionSignup.getLeaderName() != null) {
                raceCompetitionSignup.setParticipantName(raceCompetitionSignup.getLeaderName());
            }
            if (raceCompetitionSignup.getLeaderPhone() != null) {
                raceCompetitionSignup.setContactPhone(raceCompetitionSignup.getLeaderPhone());
            }
            if (raceCompetitionSignup.getLeaderEmail() != null) {
                raceCompetitionSignup.setContactEmail(raceCompetitionSignup.getLeaderEmail());
            }
            if (raceCompetitionSignup.getLeaderSchool() != null) {
                raceCompetitionSignup.setSchoolName(raceCompetitionSignup.getLeaderSchool());
            }
            if (raceCompetitionSignup.getLeaderDepartment() != null) {
                raceCompetitionSignup.setDepartment(raceCompetitionSignup.getLeaderDepartment());
            }
            if (raceCompetitionSignup.getLeaderMajor() != null) {
                raceCompetitionSignup.setMajor(raceCompetitionSignup.getLeaderMajor());
            }
            if (raceCompetitionSignup.getLeaderStudentId() != null) {
                raceCompetitionSignup.setStudentId(raceCompetitionSignup.getLeaderStudentId());
            }
            if (raceCompetitionSignup.getLeaderIdCard() != null) {
                raceCompetitionSignup.setIdCard(raceCompetitionSignup.getLeaderIdCard());
            }
            if (raceCompetitionSignup.getLeaderStudentCardUrl() != null) {
                raceCompetitionSignup.setStudentCardUrl(raceCompetitionSignup.getLeaderStudentCardUrl());
            }
            if (raceCompetitionSignup.getLeaderIdCardUrl() != null) {
                raceCompetitionSignup.setIdCardUrl(raceCompetitionSignup.getLeaderIdCardUrl());
            }
            
            // 调试：打印映射后的数据
            System.out.println("=== 字段映射后调试 ===");
            System.out.println("参赛者姓名: " + raceCompetitionSignup.getParticipantName());
            System.out.println("学号: " + raceCompetitionSignup.getStudentId());
            System.out.println("身份证号: " + raceCompetitionSignup.getIdCard());
            System.out.println("身份证URL: " + raceCompetitionSignup.getIdCardUrl());
            
            // 检查团队人数限制
            if (raceCompetitionSignup.getTeamMemberCount() != null) {
                // 获取竞赛规则中的最大人数限制
                Long maxParticipants = raceCompetitionRulesService.getMaxParticipantsByCompetitionId(raceCompetitionSignup.getCompetitionId());
                if (maxParticipants != null && raceCompetitionSignup.getTeamMemberCount() > maxParticipants) {
                    throw new RuntimeException("团队成员数量超过限制，最大允许" + maxParticipants + "人");
                }
            }
        } else {
            raceCompetitionSignup.setTeamLeader(0); // 个人赛
            raceCompetitionSignup.setTeamMemberCount(1); // 个人赛固定为1人
        }
        
        // 插入报名信息
        int result = raceCompetitionSignupMapper.insertRaceCompetitionSignup(raceCompetitionSignup);
        
        // 如果是团队赛且有团队成员信息，则保存团队成员信息
        if (result > 0 && raceCompetitionSignup.getSignupType() == 2 && 
            raceCompetitionSignup.getTeamMembers() != null && 
            !raceCompetitionSignup.getTeamMembers().isEmpty()) {
            
            for (RaceCompetitionTeamMember teamMember : raceCompetitionSignup.getTeamMembers()) {
                teamMember.setSignupId(raceCompetitionSignup.getId());
                teamMember.setIsLeader(0); // 团队成员不是队长
                raceCompetitionTeamMemberService.insertRaceCompetitionTeamMember(teamMember);
            }
        }
        
        return result;
    }

    /**
     * 修改竞赛报名信息
     * 
     * @param raceCompetitionSignup 竞赛报名信息
     * @return 结果
     */
    @Override
    public int updateRaceCompetitionSignup(RaceCompetitionSignup raceCompetitionSignup)
    {
        // 调试：打印接收到的更新数据
        System.out.println("=== 更新报名信息调试 ===");
        System.out.println("报名类型: " + raceCompetitionSignup.getSignupType());
        System.out.println("队长姓名: " + raceCompetitionSignup.getLeaderName());
        System.out.println("队长学号: " + raceCompetitionSignup.getLeaderStudentId());
        System.out.println("队长身份证: " + raceCompetitionSignup.getLeaderIdCard());
        System.out.println("队长身份证URL: " + raceCompetitionSignup.getLeaderIdCardUrl());
        
        raceCompetitionSignup.setUpdateTime(new Date());
        
        // 如果是团队赛，需要将队长信息映射到报名信息表字段
        if (raceCompetitionSignup.getSignupType() == 2) {
            // 将队长信息映射到报名信息表字段
            if (raceCompetitionSignup.getLeaderName() != null) {
                raceCompetitionSignup.setParticipantName(raceCompetitionSignup.getLeaderName());
            }
            if (raceCompetitionSignup.getLeaderPhone() != null) {
                raceCompetitionSignup.setContactPhone(raceCompetitionSignup.getLeaderPhone());
            }
            if (raceCompetitionSignup.getLeaderEmail() != null) {
                raceCompetitionSignup.setContactEmail(raceCompetitionSignup.getLeaderEmail());
            }
            if (raceCompetitionSignup.getLeaderSchool() != null) {
                raceCompetitionSignup.setSchoolName(raceCompetitionSignup.getLeaderSchool());
            }
            if (raceCompetitionSignup.getLeaderDepartment() != null) {
                raceCompetitionSignup.setDepartment(raceCompetitionSignup.getLeaderDepartment());
            }
            if (raceCompetitionSignup.getLeaderMajor() != null) {
                raceCompetitionSignup.setMajor(raceCompetitionSignup.getLeaderMajor());
            }
            if (raceCompetitionSignup.getLeaderStudentId() != null) {
                raceCompetitionSignup.setStudentId(raceCompetitionSignup.getLeaderStudentId());
            }
            if (raceCompetitionSignup.getLeaderIdCard() != null) {
                raceCompetitionSignup.setIdCard(raceCompetitionSignup.getLeaderIdCard());
            }
            if (raceCompetitionSignup.getLeaderStudentCardUrl() != null) {
                raceCompetitionSignup.setStudentCardUrl(raceCompetitionSignup.getLeaderStudentCardUrl());
            }
            if (raceCompetitionSignup.getLeaderIdCardUrl() != null) {
                raceCompetitionSignup.setIdCardUrl(raceCompetitionSignup.getLeaderIdCardUrl());
            }
            
            // 调试：打印映射后的数据
            System.out.println("=== 更新字段映射后调试 ===");
            System.out.println("参赛者姓名: " + raceCompetitionSignup.getParticipantName());
            System.out.println("学号: " + raceCompetitionSignup.getStudentId());
            System.out.println("身份证号: " + raceCompetitionSignup.getIdCard());
            System.out.println("身份证URL: " + raceCompetitionSignup.getIdCardUrl());
        }
        
        // 如果是团队赛且有团队成员信息，先删除旧的团队成员信息，再保存新的
        if (raceCompetitionSignup.getSignupType() == 2 && 
            raceCompetitionSignup.getTeamMembers() != null) {
            
            // 删除旧的团队成员信息
            raceCompetitionTeamMemberService.deleteTeamMembersBySignupId(raceCompetitionSignup.getId());
            
            // 保存新的团队成员信息
            for (RaceCompetitionTeamMember teamMember : raceCompetitionSignup.getTeamMembers()) {
                teamMember.setSignupId(raceCompetitionSignup.getId());
                teamMember.setIsLeader(0); // 团队成员不是队长
                raceCompetitionTeamMemberService.insertRaceCompetitionTeamMember(teamMember);
            }
        }
        
        return raceCompetitionSignupMapper.updateRaceCompetitionSignup(raceCompetitionSignup);
    }

    /**
     * 批量删除竞赛报名信息
     * 
     * @param ids 需要删除的竞赛报名信息主键
     * @return 结果
     */
    @Override
    public int deleteRaceCompetitionSignupByIds(Long[] ids)
    {
        // 先删除关联的团队成员信息
        for (Long id : ids) {
            System.out.println("删除报名信息ID: " + id + "，先删除关联的团队成员信息");
            int deletedMembers = raceCompetitionTeamMemberService.deleteTeamMembersBySignupId(id);
            System.out.println("删除了 " + deletedMembers + " 个团队成员");
        }
        
        int result = raceCompetitionSignupMapper.deleteRaceCompetitionSignupByIds(ids);
        System.out.println("删除了 " + result + " 个报名信息");
        return result;
    }

    /**
     * 删除竞赛报名信息信息
     * 
     * @param id 竞赛报名信息主键
     * @return 结果
     */
    @Override
    public int deleteRaceCompetitionSignupById(Long id)
    {
        // 先删除关联的团队成员信息
        System.out.println("删除报名信息ID: " + id + "，先删除关联的团队成员信息");
        int deletedMembers = raceCompetitionTeamMemberService.deleteTeamMembersBySignupId(id);
        System.out.println("删除了 " + deletedMembers + " 个团队成员");
        
        int result = raceCompetitionSignupMapper.deleteRaceCompetitionSignupById(id);
        System.out.println("删除了 " + result + " 个报名信息");
        return result;
    }

    /**
     * 根据竞赛ID查询报名信息
     * 
     * @param competitionId 竞赛ID
     * @return 报名信息列表
     */
    @Override
    public List<RaceCompetitionSignup> selectRaceCompetitionSignupByCompetitionId(Long competitionId)
    {
        return raceCompetitionSignupMapper.selectRaceCompetitionSignupByCompetitionId(competitionId);
    }

    /**
     * 根据姓名查询报名信息
     * 
     * @param participantName 参赛者姓名
     * @return 报名信息列表
     */
    @Override
    public List<RaceCompetitionSignup> selectRaceCompetitionSignupByName(String participantName)
    {
        return raceCompetitionSignupMapper.selectRaceCompetitionSignupByName(participantName);
    }

    /**
     * 根据学校查询报名信息
     * 
     * @param schoolName 学校名称
     * @return 报名信息列表
     */
    @Override
    public List<RaceCompetitionSignup> selectRaceCompetitionSignupBySchool(String schoolName)
    {
        return raceCompetitionSignupMapper.selectRaceCompetitionSignupBySchool(schoolName);
    }

    /**
     * 统计竞赛报名数量
     * 
     * @param competitionId 竞赛ID
     * @return 报名数量
     */
    @Override
    public Long countSignupByCompetitionId(Long competitionId)
    {
        return raceCompetitionSignupMapper.countSignupByCompetitionId(competitionId);
    }

    /**
     * 统计团队报名数量
     * 
     * @param competitionId 竞赛ID
     * @return 团队报名数量
     */
    @Override
    public Long countTeamSignupByCompetitionId(Long competitionId)
    {
        return raceCompetitionSignupMapper.countTeamSignupByCompetitionId(competitionId);
    }

    /**
     * 统计个人报名数量
     * 
     * @param competitionId 竞赛ID
     * @return 个人报名数量
     */
    @Override
    public Long countIndividualSignupByCompetitionId(Long competitionId)
    {
        return raceCompetitionSignupMapper.countIndividualSignupByCompetitionId(competitionId);
    }

    /**
     * 获取报名统计信息
     * 
     * @param competitionId 竞赛ID
     * @return 统计信息
     */
    @Override
    public Map<String, Object> getSignupStatistics(Long competitionId)
    {
        return raceCompetitionSignupMapper.getSignupStatistics(competitionId);
    }

    /**
     * 检查报名是否重复
     * 
     * @param raceCompetitionSignup 报名信息
     * @return 是否重复
     */
    @Override
    public boolean checkDuplicateSignup(RaceCompetitionSignup raceCompetitionSignup)
    {
        Long count = raceCompetitionSignupMapper.checkDuplicateSignup(raceCompetitionSignup);
        return count > 0;
    }

    /**
     * 审核报名信息
     * 
     * @param id 报名ID
     * @param status 审核状态
     * @param auditRemark 审核备注
     * @return 结果
     */
    @Override
    public int auditSignup(Long id, Integer status, String auditRemark)
    {
        RaceCompetitionSignup signup = new RaceCompetitionSignup();
        signup.setId(id);
        signup.setStatus(status);
        signup.setAuditRemark(auditRemark);
        signup.setAuditTime(new Date());
        signup.setAuditBy(SecurityUtils.getUsername());
        signup.setUpdateTime(new Date());
        return raceCompetitionSignupMapper.updateRaceCompetitionSignup(signup);
    }

    /**
     * 取消报名
     * 
     * @param id 报名ID
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int cancelSignup(Long id, Long userId)
    {
        RaceCompetitionSignup signup = raceCompetitionSignupMapper.selectRaceCompetitionSignupById(id);
        if (signup == null) {
            throw new RuntimeException("报名记录不存在");
        }
        if (!signup.getUserId().equals(userId)) {
            throw new RuntimeException("无权限取消此报名");
        }
        if (signup.getStatus() != 0) {
            throw new RuntimeException("只有待审核状态的报名才能取消");
        }
        
        // 软删除报名记录
        signup.setDelFlag("2");
        signup.setUpdateTime(new Date());
        return raceCompetitionSignupMapper.updateRaceCompetitionSignup(signup);
    }

    /**
     * 根据用户ID统计报名数量
     * 
     * @param userId 用户ID
     * @return 报名数量
     */
    @Override
    public Long countSignupByUserId(Long userId)
    {
        System.out.println("统计用户报名次数 - 用户ID: " + userId);
        Long count = raceCompetitionSignupMapper.countSignupByUserId(userId);
        System.out.println("用户报名次数统计结果: " + count);
        return count;
    }

    /**
     * 根据用户ID统计获奖数量
     * 
     * @param userId 用户ID
     * @return 获奖数量
     */
    @Override
    public Long countAwardByUserId(Long userId)
    {
        return raceCompetitionSignupMapper.countAwardByUserId(userId);
    }

    /**
     * 检查手机号是否已报名指定竞赛
     * 
     * @param competitionId 竞赛ID
     * @param phone 手机号
     * @return 是否已报名
     */
    @Override
    public boolean checkPhoneRegistration(Long competitionId, String phone)
    {
        return raceCompetitionSignupMapper.checkPhoneRegistration(competitionId, phone) > 0;
    }

    /**
     * 检查学号报名冲突（同一天竞赛时间冲突）
     * 
     * @param competitionId 竞赛ID
     * @param studentId 学号
     * @return 是否有冲突
     */
    @Override
    public boolean checkRegistrationConflict(Long competitionId, String studentId)
    {
        return raceCompetitionSignupMapper.checkRegistrationConflict(competitionId, studentId) > 0;
    }

    /**
     * 根据当前登录用户手机号查询报名详情
     * 
     * @return 报名记录列表
     */
    @Override
    public List<RaceCompetitionSignup> getRegistrationsByCurrentUserPhone()
    {
        // 获取当前登录用户信息
        String currentUserPhone = SecurityUtils.getLoginUser().getUser().getPhonenumber();
        System.out.println("查询当前用户手机号报名详情 - 手机号: " + currentUserPhone);
        
        if (currentUserPhone == null || currentUserPhone.trim().isEmpty()) {
            System.out.println("当前用户手机号为空，无法查询报名详情");
            return new ArrayList<>();
        }
        
        List<RaceCompetitionSignup> registrations = raceCompetitionSignupMapper.getRegistrationsByPhone(currentUserPhone);
        System.out.println("查询到报名记录数量: " + registrations.size());
        
        return registrations;
    }
}
